package com.my.vote.repository;

import java.util.List;

import javax.transaction.Transactional;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;

import com.my.vote.entity.VoteAnswer;

public interface VoteAnswerRepository extends JpaRepository<VoteAnswer, String> {

	@Query(value = " select o from VoteAnswer o where o.delFlag = 0 and o.subjectId =?1 and o.voterId =?2 ")
	List<VoteAnswer> findAllBySubjectId(String subjectId, String voterId);

	@Query(value = " select o from VoteAnswer o where o.delFlag = 0 and o.questionId =?1 and o.voterId =?2 ")
	List<VoteAnswer> findAllByQuestionId(String questionId, String voterId);

	@Query(value = " select o from VoteAnswer o where o.delFlag = 0 and o.subjectId =?1 and o.questionId =?2 and o.answer =?3 and o.voterId =?4 ")
	List<VoteAnswer> findBySubjectAndQuestionAndOptionId(String subjectId, String questionId, String optionId, String voterId);

	@Transactional
	@Modifying(clearAutomatically = true)
	@Query(value = " update VoteAnswer o set o.delFlag = 1 where o.delFlag = 0 and o.subjectId =?1 ")
	void deleteAllBySubjectId(String subjectId, String voterId);

	@Transactional
	@Modifying(clearAutomatically = true)
	@Query(value = " update VoteAnswer o set o.delFlag = 1 where o.delFlag = 0 and o.id =?1 ")
	void deleteById(String id);

	@Query(value = " select COUNT(DISTINCT voterId) from VoteAnswer where subjectId = ?1 and delFlag = 0 ")
	int voteCount(String subjectId);

	@Query(value = " select COUNT(*) from VoteAnswer where answer = ?1 and delFlag = 0 ")
	int voteCountOption(String optionId);

}
